﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RGoodSW.Logger.Interfaces;
using CodeCamp.Infrastructure;
using CodeCamp.Models.Email;
using CodeCamp.Models.Shared;
using CCM = CodeCamp.Model;
using CCMA = CodeCamp.Mailers;
using CCMUM = CodeCamp.Models.UserMailer;
using MM = Mvc.Mailer;

namespace CodeCamp.Controllers
{
    [CustomAuthorize(Roles = CCRoles.RoleNames.BigCheeze)]
    public class EmailController : ControllerBase
    {
        private static class Tags
        {
            internal const string EmailCampaignsMessage = "EmailCampaignsMessage";
            internal const string SendResultMessage = "SendResultMessage";
        }

        public EmailController(IDefaultValueProvider defaultValueProvider, ILoggerExtended logger)
            : base(defaultValueProvider, logger)
        {
        }

        private CCMA.IUserMailer _userMailer;
        protected CCMA.IUserMailer UserMailer
        {
            get
            {
                if (_userMailer == null)
                    _userMailer = new CCMA.UserMailer();
                return _userMailer;
            }
        }

        //
        // GET: /Email/

        public ActionResult Index(string eventName)
        {
            using (var ccdr = new CodeCampDataRepository())
            {
                var ccEvent = EventsHelper.GetEvent(ccdr, eventName, DefaultEventShortName, false);
                if (ccEvent.ShortName != eventName)
                    return RedirectToAction("Index", "Home", new { eventName = DefaultEventShortName });

                SetSharedViewBagProperties(ccEvent);
                CommonViewModel model = new CommonViewModel();
                SetSharedEventProperties(ccEvent, model, ccdr);
                return View(model);
            }
        }

        public ActionResult EmailCampaigns(string eventName)
        {
            using (var ccdr = new CodeCampDataRepository())
            {
                var ccEvent = EventsHelper.GetEvent(ccdr, eventName, DefaultEventShortName, false);
                if (ccEvent.ShortName != eventName)
                    return RedirectToAction("Index", "Home", new { eventName = DefaultEventShortName });

                SetSharedViewBagProperties(ccEvent);
                MailCampaignsViewModel model = new MailCampaignsViewModel()
                {
                    CampaignList = new List<MailCampaignListItem>()
                };
                var ecList = ccdr.EFContext.EmailCampaigns.Where(ec => ec.EventId == ccEvent.Id).ToList();
                int sentStatusId = (int)CCM.EmailItem.EmailSendStatus.Sent;
                foreach (var item in ecList)
                {
                    MailCampaignListItem clItem = new MailCampaignListItem(item);
                    clItem.EmailsTotal = item.EmailItems.Count();
                    clItem.EmailsSent = ccdr.EFContext.EmailItems
                                        .Where(ei => ei.EmailCampaignId.HasValue
                                            && (ei.EmailCampaignId.Value == item.Id)
                                            && (ei.SendStatusId == sentStatusId))
                                        .Count();
                    switch (clItem.Status)
                    {
                        case CCM.EmailCampaign.EmailCampaignStatus.Ongoing:
                        case CCM.EmailCampaign.EmailCampaignStatus.Pending:
                            clItem.EnableAddEmail = true;
                            clItem.EnableEdit = true;
                            clItem.EnableListEmails = true;
                            break;
                        case CCM.EmailCampaign.EmailCampaignStatus.Active:
                        case CCM.EmailCampaign.EmailCampaignStatus.Hold:
                            clItem.EnableEdit = true;
                            clItem.EnableListEmails = true;
                            break;
                        case CCM.EmailCampaign.EmailCampaignStatus.Undefined:
                            clItem.EnableEdit = true;
                            break;
                        case CCM.EmailCampaign.EmailCampaignStatus.Completed:
                            clItem.EnableEdit = true;
                            clItem.EnableListEmails = true;
                            break;
                    }
                    model.CampaignList.Add(clItem);
                }
                if (TempData.ContainsKey(Tags.EmailCampaignsMessage))
                {
                    model.MailCampaignsMessage = TempData[Tags.EmailCampaignsMessage] as string;
                }

                SetSharedEventProperties(ccEvent, model, ccdr);
                return View(model);
            }
        }

        internal static EmailItemListItem CreateEmailItemListItem(CCM.EmailItem item)
        {
            EmailItemListItem newItem = new EmailItemListItem()
            {
                CanSendFromList = CanSendEmailFromList(item),
                EmailCampaignId = item.EmailCampaignId,
                EmailItemId = item.Id,
                EmailTo = item.EmailTo,
                EmailView = item.EmailView,
                EventId = item.EventId,
                EventShortName = item.Event.ShortName,
                FirstName = item.FirstName,
                LastName = item.LastName,
                PresenterId = item.PresenterId,
                ReplyToAddress = item.ReplyToAddress,
                SentBy = item.SentBy,
                SendStatus = item.SendStatus,
                SentUTC = item.SentUTC,
                SiteUserId = item.SiteUserId,
                SubjectToUse = item.SubjectToUse
            };
            return newItem;
        }

        internal static List<EmailItemListItem> GetEmailItemsList(List<CCM.EmailItem> items)
        {
            List<EmailItemListItem> itemList = new List<EmailItemListItem>();
            foreach (var item in items)
            {
                itemList.Add(CreateEmailItemListItem(item));
            }
            return itemList;
        }

        public ActionResult RecentEmails(string eventName)
        {
            using (var ccdr = new CodeCampDataRepository())
            {
                var ccEvent = EventsHelper.GetEvent(ccdr, eventName, DefaultEventShortName, false);
                if (ccEvent.ShortName != eventName)
                    return RedirectToAction("Index", "Home", new { eventName = DefaultEventShortName });

                SetSharedViewBagProperties(ccEvent);

                var emailItems = ccdr.EFContext.EmailItems
                    .Where(ei => ei.EventId == ccEvent.Id)
                    .OrderByDescending(ei => ei.Id)
                    .Take(30)
                    .ToList();
                
                EmailItemsListViewModel model = new EmailItemsListViewModel()
                {
                    EmailItems = GetEmailItemsList(emailItems)
                };

                SetSharedEventProperties(ccEvent, model, ccdr);
                return View(model);
            }
        }

        public ActionResult EmailCampaignAdd(string eventName)
        {
            using (var repository = new CodeCampDataRepository())
            {
                var ccEvent = EventsHelper.GetEvent(repository, eventName, DefaultEventShortName, false);
                if (ccEvent.ShortName != eventName)
                    return RedirectToAction("Index", "Home", new { eventName = DefaultEventShortName });

                SetSharedViewBagProperties(ccEvent);
                MailCampaignEditViewModel model = new MailCampaignEditViewModel()
                {
                    Campaign = new EmailCampaignEditModel()
                };
                SetSharedEventProperties(ccEvent, model, repository);
                return View(model);
            }
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult EmailCampaignAdd(string eventName, EmailCampaignEditModel model)
        {
            using (var ccdr = new CodeCampDataRepository())
            {
                var ccEvent = EventsHelper.GetEvent(ccdr, eventName, DefaultEventShortName, false);
                if (ccEvent.ShortName != eventName)
                    return RedirectToAction("Index", "Home", new { eventName = DefaultEventShortName });

                var siteUserPerformingAction = GetSiteUser(ccdr, this.User, true);
                if (ModelState.IsValid)
                {
                    CCM.EmailCampaign ec = new CCM.EmailCampaign()
                    {
                        CampaignStatus = model.Status,
                        CreatedBy = UpdateUser(siteUserPerformingAction),
                        Description = model.Description,
                        EmailView = model.EmailView,
                        Event = ccEvent,
                        RecipientType = model.RecipientType,
                        ReplyToAddress = model.ReplyToAddress,
                        Salutation = model.Salutation,
                        Subject = model.Subject
                    };
                    ccdr.EFContext.EmailCampaigns.Add(ec);
                    ccdr.Save();
                    return RedirectToAction("EmailCampaigns");
                }
                SetSharedViewBagProperties(ccEvent);
                MailCampaignEditViewModel viewModel = new MailCampaignEditViewModel()
                {
                    CanAddEmails = CanAddEmailToCampaign(model.Status),
                    Campaign = model
                };
                SetSharedEventProperties(ccEvent, viewModel, ccdr);
                return View(viewModel);
            }
        }

        public ActionResult EmailCampaignEdit(string eventName, int id)
        {
            using (var ccdr = new CodeCampDataRepository())
            {
                var ccEvent = EventsHelper.GetEvent(ccdr, eventName, DefaultEventShortName, false);
                if (ccEvent.ShortName != eventName)
                    return RedirectToAction("Index", "Home", new { eventName = DefaultEventShortName });

                CCM.EmailCampaign campaign = ccdr.EFContext.EmailCampaigns.Where(ec => ec.Id == id).FirstOrDefault();
                if (campaign == null)
                    return RedirectToAction("EmailCampaigns");

                SetSharedViewBagProperties(ccEvent);
                MailCampaignEditViewModel model = new MailCampaignEditViewModel()
                {
                    CanAddEmails = CanAddEmailToCampaign(campaign),
                    CanEditCampaignConfiguration = CanEditCampaignConfiguration(campaign),
                    Campaign = new EmailCampaignEditModel(campaign)
                };
                SetSharedEventProperties(ccEvent, model, ccdr);
                return View(model);
            }
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult EmailCampaignEdit(string eventName, EmailCampaignEditModel model)
        {
            using (var ccdr = new CodeCampDataRepository())
            {
                var ccEvent = EventsHelper.GetEvent(ccdr, eventName, DefaultEventShortName, false);
                if (ccEvent.ShortName != eventName)
                    return RedirectToAction("Index", "Home", new { eventName = DefaultEventShortName });

                CCM.EmailCampaign campaign = ccdr.EFContext.EmailCampaigns.Where(ec => ec.Id == model.Id).FirstOrDefault();
                if (campaign == null)
                    return RedirectToAction("EmailCampaigns");

                var siteUserPerformingAction = GetSiteUser(ccdr, this.User, true);

                if (ModelState.IsValid)
                {
                    if (CanEditCampaignConfiguration(campaign))
                    {
                        campaign.Description = model.Description;
                        campaign.EmailView = model.EmailView;
                        campaign.RecipientType = model.RecipientType;
                        campaign.ReplyToAddress = model.ReplyToAddress;
                        campaign.Salutation = model.Salutation;
                        campaign.Subject = model.Subject;
                    }
                    campaign.CampaignStatus = model.Status;
                    campaign.UpdatedBy = UpdateUser(siteUserPerformingAction);
                    campaign.UpdatedUTC = DateTime.UtcNow;
                    ccdr.Save();
                    return RedirectToAction("EmailCampaigns");
                }
                SetSharedViewBagProperties(ccEvent);
                MailCampaignEditViewModel viewModel = new MailCampaignEditViewModel()
                {
                    CanAddEmails = CanAddEmailToCampaign(campaign),
                    Campaign = model
                };
                SetSharedEventProperties(ccEvent, viewModel, ccdr);
                return View(viewModel);
            }
        }

        private class EmailEditState
        {
            internal bool EnableEmailEditFromPreview { get; set; }
            internal bool EnableStatusEdit { get; set; }
            internal bool EnableStatusView { get; set; }
            internal bool EnableTestMessageEdit { get; set; }
        }

        private EmailEditState GetEmailEditState(CCM.EmailItem emailItem)
        {
            EmailEditState editState = new EmailEditState();

            switch (emailItem.SendStatus)
            {
                case CCM.EmailItem.EmailSendStatus.Cancelled:
                case CCM.EmailItem.EmailSendStatus.Sent:
                    editState.EnableStatusView = true;
                    break;
                case CCM.EmailItem.EmailSendStatus.BadToAddress:
                case CCM.EmailItem.EmailSendStatus.NotYetSent:
                case CCM.EmailItem.EmailSendStatus.SendError:
                    editState.EnableEmailEditFromPreview = true;
                    editState.EnableStatusEdit = true;
                    editState.EnableTestMessageEdit = true;
                    break;
                case CCM.EmailItem.EmailSendStatus.Undefined:
                    editState.EnableStatusEdit = true;
                    break;
            }

            return editState;
        }

        private BasicEmailEdit CreateBasicEmailEdit(CCM.EmailItem emailItem)
        {
            EmailEditState editState = GetEmailEditState(emailItem);

            BasicEmailEdit editModel = new BasicEmailEdit()
            {
                EnableSendStatusEdit = editState.EnableStatusEdit,
                EnableSendStatusView = editState.EnableStatusView,
                EnableTestMessageEdit = editState.EnableTestMessageEdit,
                EmailCampaignId = emailItem.EmailCampaignId,
                EmailView = emailItem.EmailView,
                CustomContent1 = emailItem.CustomContent1,
                CustomContent2 = emailItem.CustomContent2,
                EmailItemId = emailItem.Id,
                EmailTo = emailItem.EmailTo,
                FirstName = emailItem.FirstName,
                LastName = emailItem.LastName,
                ReplyToAddress = emailItem.ReplyToAddress,
                Salutation = emailItem.Salutation,
                SendStatus = emailItem.SendStatus,
                Subject = emailItem.Subject,
                TestMessage = emailItem.TestMessage
            };
            return editModel;
        }

        private void UpdateEmailEditState(CCM.EmailItem emailItem, BasicEmailEdit basicEmailEdit)
        {
            EmailEditState editState = GetEmailEditState(emailItem);
            basicEmailEdit.EnableSendStatusEdit = editState.EnableStatusEdit;
            basicEmailEdit.EnableSendStatusView = editState.EnableStatusView;
            basicEmailEdit.EnableTestMessageEdit = editState.EnableTestMessageEdit;
        }

        private EmailItemEditViewModel CreateEmailItemEditViewModel(CCM.EmailItem emailItem)
        {
            EmailItemEditViewModel model = new EmailItemEditViewModel()
            {
                MailModel = CreateBasicEmailEdit(emailItem)
            };
            FillAdditionalEmailItemEditViewModelValues(model, emailItem);
            return model;
        }

        private void FillAdditionalEmailItemEditViewModelValues(EmailItemEditViewModel model, CCM.EmailCampaign emailCampaign)
        {
            if (emailCampaign != null)
            {
                model.MailModel.CampaignDescription = emailCampaign.Description;
                model.MailModel.CampaignRecipientType = emailCampaign.RecipientType;
                model.MailModel.CampaignStatus = emailCampaign.CampaignStatus;
            }
        }

        private void FillAdditionalEmailItemEditViewModelValues(EmailItemEditViewModel model, CCM.EmailItem emailItem)
        {
            if (emailItem.EmailCampaignId.HasValue)
            {
                FillAdditionalEmailItemEditViewModelValues(model, emailItem.EmailCampaign);
            }
        }

        private bool CanAddEmailToCampaign(CCM.EmailCampaign.EmailCampaignStatus campaignStatus)
        {
            if ((campaignStatus == CCM.EmailCampaign.EmailCampaignStatus.Pending)
                || (campaignStatus == CCM.EmailCampaign.EmailCampaignStatus.Ongoing))
            {
                return true;
            }
            return false;
        }

        private bool CanAddEmailToCampaign(CCM.EmailCampaign campaign)
        {
            if (campaign != null)
            {
                return CanAddEmailToCampaign(campaign.CampaignStatus);
            }
            return false;
        }

        private bool CanEditCampaignConfiguration(CCM.EmailCampaign.EmailCampaignStatus campaignStatus)
        {
            switch (campaignStatus)
            {
                case CCM.EmailCampaign.EmailCampaignStatus.Active:
                case CCM.EmailCampaign.EmailCampaignStatus.Cancelled:
                case CCM.EmailCampaign.EmailCampaignStatus.Completed:
                case CCM.EmailCampaign.EmailCampaignStatus.Hold:
                case CCM.EmailCampaign.EmailCampaignStatus.Ongoing:
                    return false;
                case CCM.EmailCampaign.EmailCampaignStatus.Pending:
                    return true;
                default:
                    return false;
            }
        }

        private bool CanEditCampaignConfiguration(CCM.EmailCampaign campaign)
        {
            if (campaign != null)
            {
                return CanEditCampaignConfiguration(campaign.CampaignStatus);
            }
            return false;
        }

        public ActionResult EmailCampaignEmailList(string eventName, int id)
        {
            using (var ccdr = new CodeCampDataRepository())
            {
                var ccEvent = EventsHelper.GetEvent(ccdr, eventName, DefaultEventShortName, false);
                if (ccEvent.ShortName != eventName)
                    return RedirectToAction("Index", "Home", new { eventName = DefaultEventShortName });
                var campaign = ccdr.EFContext.EmailCampaigns
                    .Where(c => c.EventId == ccEvent.Id && c.Id == id)
                    .FirstOrDefault();
                if (campaign == null)
                    return RedirectToAction("EmailCampaigns");

                SetSharedViewBagProperties(ccEvent);

                var items = ccdr.EFContext.EmailItems
                    .Where(ei => ei.EmailCampaignId == campaign.Id && ei.EventId == ccEvent.Id)
                    .ToList();

                EmailItemsListWithSearchViewModel model = new EmailItemsListWithSearchViewModel()
                {
                    CanAddEmailsToCampaign = CanAddEmailToCampaign(campaign),
                    EmailCampaignDescription = campaign.Description,
                    EmailCampaignId = campaign.Id,
                    EmailCampaignStatus = campaign.CampaignStatus,
                    EmailItems = GetEmailItemsList(items),
                    SearchModel = new EmailAddSearch()
                    {
                        EmailCampaignId = campaign.Id,
                        ExcludeSiteUsersInCampaign = true
                    }
                };
#if USE_WIF
                model.SearchModel.ExcludeCodeCampIdentities = true;
#endif
                if (TempData.ContainsKey(Tags.SendResultMessage))
                    ViewBag.SendResultMessage = TempData[Tags.SendResultMessage];

                SetSharedEventProperties(ccEvent, model, ccdr);
                return View(model);
            }
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult EmailCampaignEmailList(string eventName, EmailAddSearch model)
        {
            using (var ccdr = new CodeCampDataRepository())
            {
                var ccEvent = EventsHelper.GetEvent(ccdr, eventName, DefaultEventShortName, false);
                if (ccEvent.ShortName != eventName)
                    return RedirectToAction("Index", "Home", new { eventName = DefaultEventShortName });
                var campaign = ccdr.EFContext.EmailCampaigns
                    .Where(c => c.EventId == ccEvent.Id && c.Id == model.EmailCampaignId)
                    .FirstOrDefault();
                if (campaign == null)
                    return RedirectToAction("EmailCampaigns");

                List<CCM.SiteUser> siteUserList = null;
                string resultMessage = string.Empty;
                if (ModelState.IsValid)
                {
                    //resultMessage = string.Format("First=\"{0}\", Last=\"{1}\", LNStarts={2}, PO={3}, IO={4}",
                    //    model.FirstName,
                    //    model.LastName,
                    //    model.LastNameStartsWith,
                    //    model.PresentersOnly,
                    //    model.InsidersOnly);
                    var siteUsers = ccdr.EFContext.SiteUsers
                                    .OrderBy(su => su.FirstName)
                                    .ThenBy(su => su.LastName)
                                    .AsQueryable();

                    if (model.ExcludeCodeCampIdentities)
                    {
                        siteUsers = siteUsers
                                    .Where(su => su.UserIdentityProvider != CodeCampDataRepository.IdentityIssuers.CodeCamp)
                                    .AsQueryable();
                    }
                    if (!string.IsNullOrWhiteSpace(model.FirstName))
                        siteUsers = siteUsers.Where(su => su.FirstName == model.FirstName).AsQueryable();
                    if (!string.IsNullOrWhiteSpace(model.LastName))
                    {
                        if (model.LastNameStartsWith)
                        {
                            siteUsers = siteUsers.Where(su => su.LastName.StartsWith(model.LastName)).AsQueryable();
                        }
                        else
                        {
                            siteUsers = siteUsers.Where(su => su.LastName == model.LastName).AsQueryable();
                        }
                    }
                    if (model.PresentersOnly)
                    {
                        siteUsers = from su in siteUsers
                                    let sup = su.Presenters
                                        .Where(p => p.SiteUserId.HasValue && p.SiteUserId == su.Id && p.Event.ShortName == ccEvent.ShortName)
                                        .Where(p => p.SessionPresenters.Count() > 0)
                                    where sup.Any()
                                    select su;
                    }
                    else if (model.ExcludePresenters)
                    {
                        siteUsers = from su in siteUsers
                                    let sup = su.Presenters
                                        .Where(p => p.SiteUserId.HasValue && p.SiteUserId == su.Id && p.Event.ShortName == ccEvent.ShortName)
                                        .Where(p => p.SessionPresenters.Count() > 0)
                                    where !sup.Any()
                                    select su;
                    }
                    siteUserList = siteUsers.ToList();
                    if (siteUserList.Count < 1)
                    {
                        resultMessage = "No SiteUsers found matching the specified criteria.";
                    }
                    else
                    {
                    }

                }
                else
                {
                    resultMessage = "!ModelState.IsValid";
                }

                var items = ccdr.EFContext.EmailItems
                    .Where(ei => ei.EmailCampaignId == campaign.Id && ei.EventId == ccEvent.Id)
                    .ToList();

                EmailItemsListWithSearchViewModel viewModel = new EmailItemsListWithSearchViewModel()
                {
                    CanAddEmailsToCampaign = CanAddEmailToCampaign(campaign),
                    EmailCampaignDescription = campaign.Description,
                    EmailCampaignId = campaign.Id,
                    EmailCampaignStatus = campaign.CampaignStatus,
                    EmailItems = GetEmailItemsList(items),
                    ResultMessage = resultMessage,
                    SearchModel = model
                };
                if ((siteUserList != null) && (siteUserList.Count > 0))
                {
                    viewModel.SiteUserList = new List<SiteUserListItem>();
                    foreach (var su in siteUserList)
                    {
                        var suli = new SiteUserListItem()
                        {
                            EmailCampaignId = campaign.Id,
                            SiteUserCreatedUTC = su.CreatedUTC,
                            SiteUserEmail = su.EmailAddress,
                            SiteUserId = su.Id,
                            SiteUserIdentityProvider = su.UserIdentityProvider,
                            SiteUserLastActivityUTC = su.LastOnlineActivityUTC,
                            SiteUserName = string.Concat(su.FirstName, " ", su.LastName).Trim()
                        };
                        //int presenterId = su.Presenters.Where(pr => pr.EventId == ccEvent.Id).OrderByDescending(pr => pr.Id).Select(pr => pr.Id).FirstOrDefault();
                        //if (presenterId > 0)
                        //{
                        //    suli.IsPresenterAtThisCC = true;
                        //    suli.PresenterId = presenterId;
                        //}
                        //if (ccdr.SiteUserIsInRole(su.Id, CCRoles.RoleNames.BigCheeze))
                        //    suli.IsInsider = true;
                        bool exclude = false;
                        if (model.ExcludeSiteUsersInCampaign)
                        {
                            var campaignEmailItemWithSiteUser = ccdr.EFContext.EmailItems
                                            .Where(ei => 
                                                ei.EmailCampaignId.HasValue
                                                && (ei.EmailCampaignId == campaign.Id)
                                                && (ei.SiteUserId.HasValue && ei.SiteUserId == su.Id))
                                            .FirstOrDefault();
                            if (campaignEmailItemWithSiteUser != null)
                                exclude = true;
                        }
                        if (!exclude)
                        {
                            //if (model.InsidersOnly)
                            //{
                            //    if (suli.IsInsider)
                            //    {
                            //        if (model.PresentersOnly)
                            //        {
                            //            if (suli.IsPresenterAtThisCC)
                            //                viewModel.SiteUserList.Add(suli);
                            //        }
                            //        else if (model.ExcludePresenters)
                            //        {
                            //            if (!suli.IsPresenterAtThisCC)
                            //                viewModel.SiteUserList.Add(suli);
                            //        }
                            //        else
                            //        {
                            //            viewModel.SiteUserList.Add(suli);
                            //        }
                            //    }
                            //}
                            //else if (model.PresentersOnly)
                            //{
                            //    if (suli.IsPresenterAtThisCC)
                            //        viewModel.SiteUserList.Add(suli);
                            //}
                            //else if (model.ExcludePresenters)
                            //{
                            //    if (!suli.IsPresenterAtThisCC)
                            //        viewModel.SiteUserList.Add(suli);
                            //}
                            //else
                            //{
                                viewModel.SiteUserList.Add(suli);
                            //}
                        }
                    }
                }
                SetSharedEventProperties(ccEvent, viewModel, ccdr);
                return View(viewModel);
            }
        }

        public ActionResult EmailCampaignAddEmail(string eventName, decimal id)
        {
            using (var ccdr = new CodeCampDataRepository())
            {
                var ccEvent = EventsHelper.GetEvent(ccdr, eventName, DefaultEventShortName, false);
                if (ccEvent.ShortName != eventName)
                    return RedirectToAction("Index", "Home", new { eventName = DefaultEventShortName });

                decimal wholePart = Math.Truncate(id);
                int campaignId = (int)wholePart;
                Nullable<int> siteUserId = null;
                CCM.SiteUser siteUser2Add = null;
                if (wholePart != id)
                {
                    decimal fractionPart = id - wholePart;
                    string tempId = id.ToString();
                    string rawId = null;
                    int dotIdx = tempId.IndexOf('.');
                    if (dotIdx > 0)
                    {
                        rawId = tempId.Substring(dotIdx + 1);
                    }
                    int fractionPartAsInt;
                    if (!Int32.TryParse(rawId, out fractionPartAsInt))
                    {
                        TempData[Tags.EmailCampaignsMessage] = string.Format("EmailCampaignAddEmail(\"{0}\", {1}) {2} \"{3}\", \"{4}\"",
                            eventName, id, fractionPart, tempId, rawId);
                        return RedirectToAction("EmailCampaigns");
                    }
                    else
                    {
                        campaignId = fractionPartAsInt;
                        siteUserId = (int)wholePart;
                        siteUser2Add = ccdr.GetSiteUser(siteUserId.Value);
                    }
                }

                var campaign = ccdr.EFContext.EmailCampaigns
                    .Where(c => c.EventId == ccEvent.Id && c.Id == campaignId)
                    .FirstOrDefault();
                if (campaign == null)
                {
                    TempData[Tags.EmailCampaignsMessage] = string.Format("EmailCampaignAddEmail(\"{0}\", {1}) - campaign {2} not found.",
                        eventName, id, campaignId);
                    return RedirectToAction("EmailCampaigns");
                }

                if (siteUserId.HasValue && (siteUser2Add == null))
                {
                    TempData[Tags.EmailCampaignsMessage] = string.Format("EmailCampaignAddEmail(\"{0}\", {1}) - campaign {2} found, SiteUser {3} not found.",
                        eventName, id, campaignId, siteUserId);
                    return RedirectToAction("EmailCampaigns");
                }

                SetSharedViewBagProperties(ccEvent);
                EmailItemEditViewModel model = new EmailItemEditViewModel()
                {
                    MailModel = new BasicEmailEdit()
                    {
                        EnableSendStatusView = true,
                        EmailCampaignId = campaign.Id,
                        ReplyToAddress = campaign.ReplyToAddress,
                        Salutation = campaign.Salutation,
                        SendStatus = CCM.EmailItem.EmailSendStatus.NotYetSent,
                        Subject = campaign.Subject
                    }
                };
                if (campaign.RecipientType == CCM.EmailCampaign.EmailRecipientType.Test)
                    model.MailModel.TestMessage = true;
                if (siteUser2Add != null)
                {
                    model.MailModel.EmailTo = siteUser2Add.EmailAddress;
                    model.MailModel.FirstName = siteUser2Add.FirstName;
                    model.MailModel.LastName = siteUser2Add.LastName;
                    model.MailModel.SiteUserId = siteUser2Add.Id;
                }
                FillAdditionalEmailItemEditViewModelValues(model, campaign);
                SetSharedEventProperties(ccEvent, model, ccdr);
                return View(model);
            }
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult EmailCampaignAddEmail(string eventName, BasicEmailEdit model)
        {
            using (var ccdr = new CodeCampDataRepository())
            {
                var ccEvent = EventsHelper.GetEvent(ccdr, eventName, DefaultEventShortName, false);
                if (ccEvent.ShortName != eventName)
                    return RedirectToAction("Index", "Home", new { eventName = DefaultEventShortName });
                if (!model.EmailCampaignId.HasValue)
                    return RedirectToAction("EmailCampaigns");
                var campaign = ccdr.EFContext.EmailCampaigns
                    .Where(c => c.EventId == ccEvent.Id && c.Id == model.EmailCampaignId.Value)
                    .FirstOrDefault();
                if (campaign == null)
                    return RedirectToAction("EmailCampaigns");
                var siteUserPerformingAction = GetSiteUser(ccdr, this.User, true);
                CCM.SiteUser siteUserBeingAdded = null;
                if (model.SiteUserId.HasValue)
                    siteUserBeingAdded = ccdr.GetSiteUser(model.SiteUserId.Value);

                if (ModelState.IsValid)
                {
                    //string errorMessage = null;
                    CCM.EmailItem emailItem = null;
                    if (model.EmailItemId.HasValue)
                        emailItem = ccdr.EFContext.EmailItems.Where(mi => mi.Id == model.EmailItemId.Value).FirstOrDefault();
                    if (emailItem != null)
                    {
                        emailItem.CustomContent1 = model.CustomContent1;
                        emailItem.CustomContent2 = model.CustomContent2;
                        emailItem.EmailTo = model.EmailTo;
                        emailItem.FirstName = model.FirstName;
                        emailItem.LastName = model.LastName;
                        emailItem.ReplyToAddress = model.ReplyToAddress;
                        emailItem.Salutation = model.Salutation;
                        emailItem.Subject = model.Subject;
                        if (model.EnableTestMessageEdit)
                            emailItem.TestMessage = model.TestMessage;
                    }
                    else
                    {
                        emailItem = new CCM.EmailItem()
                        {
                            CreatedBy = UpdateUser(siteUserPerformingAction),
                            CustomContent1 = model.CustomContent1,
                            CustomContent2 = model.CustomContent2,
                            EmailCampaign = campaign,
                            EmailTo = model.EmailTo,
                            EmailView = campaign.EmailView,
                            Event = ccEvent,
                            FirstName = model.FirstName,
                            LastName = model.LastName,
                            ReplyToAddress = model.ReplyToAddress,
                            Salutation = model.Salutation,
                            SendStatus = CCM.EmailItem.EmailSendStatus.NotYetSent,
                            Subject = model.Subject
                        };
                        if (campaign.RecipientType == CCM.EmailCampaign.EmailRecipientType.Test)
                            emailItem.TestMessage = true;
                        ccdr.EFContext.EmailItems.Add(emailItem);
                    }
                    if ((siteUserBeingAdded != null) && emailItem.EmailTo.Equals(siteUserBeingAdded.EmailAddress, StringComparison.CurrentCultureIgnoreCase))
                    {
                        emailItem.SiteUser = siteUserBeingAdded;
                        CCM.Presenter presenterForCurrentEvent = ccdr.GetPresenters(ccEvent.Id)
                                        .Where(pr => pr.SiteUserId == siteUserBeingAdded.Id)
                                        .FirstOrDefault();
                        if (presenterForCurrentEvent != null)
                            emailItem.Presenter = presenterForCurrentEvent;
                    }
                    ccdr.Save();
                    return RedirectToAction("EmailCampaignEmailList", new { eventName = ccEvent.ShortName, id = emailItem.EmailCampaignId.Value });
                }

                SetSharedViewBagProperties(ccEvent);
                EmailItemEditViewModel viewModel = new EmailItemEditViewModel()
                {
                    MailModel = model
                };
                FillAdditionalEmailItemEditViewModelValues(viewModel, campaign);
                SetSharedEventProperties(ccEvent, viewModel, ccdr);
                return View(viewModel);
            }
        }

        private string GetEmailEditParentContext(CCM.EmailItem emailItem)
        {
            string parentContext = null;
            if ((this.Request != null) && (this.Request.UrlReferrer != null) && !string.IsNullOrWhiteSpace(this.Request.UrlReferrer.AbsolutePath))
            {
                string referrerUrl = this.Request.UrlReferrer.AbsolutePath.ToLower();
                if ((referrerUrl.IndexOf("/emailcampaignemaillist/") > 0) && emailItem.EmailCampaignId.HasValue)
                {
                    parentContext = "CampaignList";
                }
                else if (referrerUrl.IndexOf("/recentemails") > 0)
                {
                    parentContext = "RecentEmails";
                }
            }
            return parentContext;
        }

        private void SetEmailEditParentContext(EmailItemEditViewModel editViewModel, CCM.EmailItem emailItem)
        {
            if ((this.Request != null) && (this.Request.UrlReferrer != null) && !string.IsNullOrWhiteSpace(this.Request.UrlReferrer.AbsolutePath))
            {
                string referrerUrl = this.Request.UrlReferrer.AbsolutePath.ToLower();
                editViewModel.MailModel.ParentContext = GetEmailEditParentContext(emailItem);
                if (string.IsNullOrWhiteSpace(editViewModel.MailModel.ParentContext))
                {
                    editViewModel.ErrorMessage = string.Format("ReferrerPath: \"{0}\"", referrerUrl);
                }
            }
        }

        public ActionResult EmailItemEdit(string eventName, int id)
        {
            SetLoggerThreadContextData();
            using (var ccdr = new CodeCampDataRepository())
            {
                var ccEvent = EventsHelper.GetEvent(ccdr, eventName, DefaultEventShortName, false);
                if (ccEvent.ShortName != eventName)
                    return RedirectToAction("Index", "Home", new { eventName = DefaultEventShortName });
                var emailItem = ccdr.EFContext.EmailItems
                    .Where(ei => ei.EventId == ccEvent.Id && ei.Id == id)
                    .FirstOrDefault();
                if (emailItem == null)
                    return RedirectToAction("RecentEmails");

                SetSharedViewBagProperties(ccEvent);
                var siteUserPerformingEdit = GetSiteUser(ccdr, this.User, true);

                var model = CreateEmailItemEditViewModel(emailItem);
                model.MailModel.EnableEmailViewEdit = true;
                SetSharedEventProperties(ccEvent, model, ccdr);

                SetEmailEditParentContext(model, emailItem);

                return View(model);
            }
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult EmailItemEdit(string eventName, BasicEmailEdit model)
        {
            using (var ccdr = new CodeCampDataRepository())
            {
                var ccEvent = EventsHelper.GetEvent(ccdr, eventName, DefaultEventShortName, false);
                if (ccEvent.ShortName != eventName)
                    return RedirectToAction("Index", "Home", new { eventName = DefaultEventShortName });
                if (!model.EmailCampaignId.HasValue)
                    return RedirectToAction("EmailCampaigns");
                var campaign = ccdr.EFContext.EmailCampaigns
                    .Where(c => c.EventId == ccEvent.Id && c.Id == model.EmailCampaignId.Value)
                    .FirstOrDefault();
                if (campaign == null)
                    return RedirectToAction("EmailCampaigns");
                
                var siteUserPerformingAction = GetSiteUser(ccdr, this.User, true);

                CCM.EmailItem emailItem = null;
                string errorMessage = null;
                if (ModelState.IsValid)
                {
                    emailItem = ccdr.EFContext.EmailItems
                                            .Where(mi => mi.Id == model.EmailItemId.Value).FirstOrDefault();
                    if (emailItem == null)
                    {
                        errorMessage = string.Format("Email Item with Id = {0} not found.", model.EmailItemId);
                    }
                    else
                    {
                        emailItem.CustomContent1 = model.CustomContent1;
                        emailItem.CustomContent2 = model.CustomContent2;
                        emailItem.EmailTo = model.EmailTo;
                        emailItem.FirstName = model.FirstName;
                        emailItem.LastName = model.LastName;
                        emailItem.ReplyToAddress = model.ReplyToAddress;
                        emailItem.Salutation = model.Salutation;
                        emailItem.Subject = model.Subject;
                        if (model.EnableEmailViewEdit)
                            emailItem.EmailView = model.EmailView;
                        if (model.EnableSendStatusEdit)
                            emailItem.SendStatus = model.SendStatus;
                        if (model.EnableTestMessageEdit)
                            emailItem.TestMessage = model.TestMessage;

                        ccdr.Save();
                        if (!string.IsNullOrWhiteSpace(model.ParentContext))
                        {
                            switch (model.ParentContext)
                            {
                                case "CampaignList":
                                    if (emailItem.EmailCampaignId.HasValue)
                                        return RedirectToAction("EmailCampaignEmailList", new { eventName = ccEvent.ShortName, id = emailItem.EmailCampaignId.Value });
                                    else
                                        return RedirectToAction("EmailCampaigns");
                                case "RecentEmails":
                                    return RedirectToAction("RecentEmails");
                            }
                            return RedirectToAction("Index");
                        }
                    }
                }
                SetSharedViewBagProperties(ccEvent);
                EmailItemEditViewModel viewModel = new EmailItemEditViewModel()
                {
                    ErrorMessage = errorMessage,
                    MailModel = model
                };
                UpdateEmailEditState(emailItem, viewModel.MailModel);
                if (emailItem != null)
                    FillAdditionalEmailItemEditViewModelValues(viewModel, campaign);
                SetSharedEventProperties(ccEvent, viewModel, ccdr);
                return View(viewModel);
            }
        }

        public ActionResult EmailItemPreview(string eventName, int id)
        {
            SetLoggerThreadContextData();
            using (var ccdr = new CodeCampDataRepository())
            {
                var ccEvent = EventsHelper.GetEvent(ccdr, eventName, DefaultEventShortName, false);
                if (ccEvent.ShortName != eventName)
                    return RedirectToAction("Index", "Home", new { eventName = DefaultEventShortName });
                var emailItem = ccdr.EFContext.EmailItems
                    .Where(ei => ei.EventId == ccEvent.Id && ei.Id == id)
                    .FirstOrDefault();
                if (emailItem == null)
                    return RedirectToAction("Index");

                SetSharedViewBagProperties(ccEvent);
                var siteUserPerformingEdit = GetSiteUser(ccdr, this.User, true);

                EmailPreviewViewModel model = new EmailPreviewViewModel()
                {
                    EmailItem = PrepareEmailContentItem(emailItem),
                    EmailItemId = emailItem.Id,
                    ParentContext = GetEmailEditParentContext(emailItem)
                };
                EmailEditState editState = GetEmailEditState(emailItem);
                model.EnableEditLink = editState.EnableEmailEditFromPreview;

                if (emailItem.SendStatus == CCM.EmailItem.EmailSendStatus.NotYetSent)
                    model.SendEnabled = true;

                SetSharedEventProperties(ccEvent, model, ccdr);
                return View(model);
            }
        }

        internal static EmailContentItem PrepareEmailContentItem(CCM.EmailItem emailItem)
        {
            EmailContentItem contentItem = new EmailContentItem(emailItem);
            return contentItem;
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult EmailItemPreview(string eventName, EmailPreviewViewModel model)
        {
            SetLoggerThreadContextData();
            using (var ccdr = new CodeCampDataRepository())
            {
                var ccEvent = EventsHelper.GetEvent(ccdr, eventName, DefaultEventShortName, false);
                if (ccEvent.ShortName != eventName)
                    return RedirectToAction("Index", "Home", new { eventName = DefaultEventShortName });
                var emailItem = ccdr.EFContext.EmailItems
                    .Where(ei => ei.EventId == ccEvent.Id && ei.Id == model.EmailItemId)
                    .FirstOrDefault();
                if (emailItem == null)
                    return RedirectToAction("Index");

                string parentContext = model.ParentContext;
                var siteUserPerformingAction = GetSiteUser(ccdr, this.User, true);
                model.ErrorMessage = null;
                if (ModelState.IsValid)
                {
                    string errorMessage;
                    bool sendSuccess = SendEmailMessage(ccdr, emailItem, UpdateUser(siteUserPerformingAction),
                        out errorMessage);
                    if (sendSuccess)
                    {
                        var viewModel = new MailBasicViewModel()
                        {
                            ErrorMessage = string.Format("parentContext=\"{0}\"", parentContext),
                            MailModel = CreateBasicEmailEdit(emailItem)
                        };
                        viewModel.MailModel.ParentContext = parentContext;
                        SetSharedEventProperties(ccEvent, viewModel, ccdr);
                        return View("MailSent", viewModel);
                    }
                    model.ErrorMessage = errorMessage;
                }

                model.EmailItem = PrepareEmailContentItem(emailItem);
                model.EmailItemId = emailItem.Id;
                model.ParentContext = parentContext;

                if (emailItem.SendStatus == CCM.EmailItem.EmailSendStatus.NotYetSent)
                    model.SendEnabled = true;

                SetSharedViewBagProperties(ccEvent);
                return View(model);
            }
        }

        public static bool CanSendEmailFromList(CCM.EmailItem emailItem)
        {
            if (emailItem != null)
            {
                if (emailItem.SendStatus == CCM.EmailItem.EmailSendStatus.NotYetSent)
                {
                    if (!emailItem.EmailCampaignId.HasValue)
                        return true;
                    switch (emailItem.EmailCampaign.CampaignStatus)
                    {
                        case CCM.EmailCampaign.EmailCampaignStatus.Active:
                        case CCM.EmailCampaign.EmailCampaignStatus.Ongoing:
                            return true;
                        case CCM.EmailCampaign.EmailCampaignStatus.Pending:
                            if (emailItem.EmailCampaign.RecipientType == CCM.EmailCampaign.EmailRecipientType.Test)
                                return true;
                            break;
                    }
                }
            }
            return false;
        }

        public ActionResult SendFromList(string eventName, int id)
        {
            SetLoggerThreadContextData();
            using (var ccdr = new CodeCampDataRepository())
            {
                var ccEvent = EventsHelper.GetEvent(ccdr, eventName, DefaultEventShortName, false);
                if (ccEvent.ShortName != eventName)
                    return RedirectToAction("Index", "Home", new { eventName = DefaultEventShortName });
                var emailItem = ccdr.EFContext.EmailItems
                    .Where(ei => ei.EventId == ccEvent.Id && ei.Id == id)
                    .FirstOrDefault();
                if (emailItem == null)
                    return RedirectToAction("Index");

                bool canSend = CanSendEmailFromList(emailItem);

                if (!canSend)
                {
                    if (emailItem.EmailCampaignId.HasValue)
                    {
                        string msg = string.Format("Email id {0} cannot be sent ({1}/{2}).", emailItem.Id, emailItem.EmailCampaign.CampaignStatus, emailItem.SendStatus);
                        Logger.Debug(msg);
                        TempData[Tags.SendResultMessage] = msg;
                        return @RedirectToAction("EmailCampaignEmailList", new { eventName = ccEvent.ShortName, id = emailItem.EmailCampaignId.Value });
                    }
                    else
                    {
                        string msg = string.Format("Email id {0} cannot be sent ({1}).", emailItem.Id, emailItem.SendStatus);
                        Logger.Debug(msg);
                        TempData[Tags.SendResultMessage] = msg;
                        return @RedirectToAction("RecentEmails", new { eventName = ccEvent.ShortName });
                    }
                }

                SetSharedViewBagProperties(ccEvent);
                var siteUserPerformingAction = GetSiteUser(ccdr, this.User, true);

                string errorMessage;
                bool sendSuccess = SendEmailMessage(ccdr, emailItem, UpdateUser(siteUserPerformingAction),
                    out errorMessage);

                string sendResultMessage = null;
                if (sendSuccess)
                {
                    sendResultMessage = string.Format("Email {0} sent.", emailItem.Id);
                    Logger.Debug(sendResultMessage);
                }
                else
                {
                    sendResultMessage = string.Format("Email {0} not sent.  {1}", emailItem.Id, errorMessage);
                    Logger.Info(sendResultMessage);
                }

                TempData[Tags.SendResultMessage] = sendResultMessage;
                if (emailItem.EmailCampaignId.HasValue)
                {
                    return @RedirectToAction("EmailCampaignEmailList", new { eventName = ccEvent.ShortName, id = emailItem.EmailCampaignId.Value });
                }
                else
                {
                    return @RedirectToAction("RecentEmails", new { eventName = ccEvent.ShortName });
                }

            }
        }

        public ActionResult TestBasicMail(string eventName)
        {
            SetLoggerThreadContextData();
            using (var ccdr = new CodeCampDataRepository())
            {
                var event_ = EventsHelper.GetEvent(ccdr, eventName, DefaultEventShortName, false);
                SetSharedViewBagProperties(event_);
                var siteUserPerformingTest = GetSiteUser(ccdr, this.User, true);
                MailBasicViewModel model = new MailBasicViewModel()
                {
                    MailModel = new BasicEmailEdit()
                    {
                        EnableSendStatusView = true,
                        FirstName = siteUserPerformingTest.FirstName,
                        ReplyToAddress = siteUserPerformingTest.EmailAddress,
                        SendStatus = CCM.EmailItem.EmailSendStatus.NotYetSent,
                        SubmitButtonText = "Send",
                        TestMessage = true
                    }
                };
                SetSharedEventProperties(event_, model, ccdr);
                return View("MailTest/TestBasicMail", model);
            }
        }

        private bool SendEmailMessage(CodeCampDataRepository ccdr, CCM.EmailItem emailItem,
            string updateUser,
            out string errorMessage)
        {
            errorMessage = null;
            bool sendSuccess = false;
            MM.MvcMailMessage message = null;
            try
            {
                message = UserMailer.CodeCampEventMessage(PrepareEmailContentItem(emailItem));
            }
            catch (Exception ex)
            {
                Logger.WarnFormat("EmailController.TestBasicMail emailItem.Id={1}, to=\"{2}\", subject=\"{3}\" {0}{4}: {5}",
                    Environment.NewLine, emailItem.Id, emailItem.EmailTo, emailItem.Subject, ex.GetType(), ex.Message);
                errorMessage = ex.Message;
                emailItem.SendStatus = CCM.EmailItem.EmailSendStatus.MessageCreationError;
                ccdr.Save();
            }
            if (message != null)
            {
                try
                {
                    message.Send();
                    emailItem.SendStatus = CCM.EmailItem.EmailSendStatus.Sent;
                    emailItem.SentBy = updateUser;
                    emailItem.SentUTC = DateTime.UtcNow;
                    ccdr.Save();
                    sendSuccess = true;
                }
                catch (System.Net.Mail.SmtpFailedRecipientException ex)
                {
                    emailItem.SendStatus = CCM.EmailItem.EmailSendStatus.BadToAddress;
                    Logger.ErrorFormat(ex, "EmailController.TestBasicMail emailItem.Id={1}, itemStatus={2}, emailStatusCode={3}, to=\"{4}\", subject=\"{5}\" {0}{6}: {7}",
                        Environment.NewLine, emailItem.Id, emailItem.SendStatus, ex.StatusCode,
                        emailItem.EmailTo, emailItem.Subject, ex.GetType(), ex.Message);
                    errorMessage = ex.Message;
                    ccdr.Save();
                }
                catch (Exception ex)
                {
                    emailItem.SendStatus = CCM.EmailItem.EmailSendStatus.SendError;
                    Logger.ErrorFormat(ex, "EmailController.TestBasicMail emailItem.Id={1}, itemStatus={2}, to=\"{3}\", subject=\"{4}\" {0}{5}: {6}",
                        Environment.NewLine, emailItem.Id, emailItem.SendStatus,
                        emailItem.EmailTo, emailItem.Subject, ex.GetType(), ex.Message);
                    errorMessage = ex.Message;
                    ccdr.Save();
                }
            }
            return sendSuccess;
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult TestBasicMail(string eventName, BasicEmailEdit model)
        {
            SetLoggerThreadContextData();
            using (var ccdr = new CodeCampDataRepository())
            {
                MailBasicViewModel viewModel = null;
                var event_ = EventsHelper.GetEvent(ccdr, eventName, DefaultEventShortName, false);
                var siteUserPerformingTest = GetSiteUser(ccdr, this.User, true);
                if (ModelState.IsValid)
                {
                    bool sendSuccess = false;
                    string errorMessage = null;
                    CCM.EmailItem emailItem = null;
                    if (model.EmailItemId.HasValue)
                        emailItem = ccdr.EFContext.EmailItems.Where(mi => mi.Id == model.EmailItemId.Value).FirstOrDefault();
                    if (emailItem != null)
                    {
                        emailItem.CustomContent1 = model.CustomContent1;
                        emailItem.CustomContent2 = model.CustomContent2;
                        emailItem.EmailTo = model.EmailTo;
                        emailItem.FirstName = model.FirstName;
                        emailItem.LastName = model.LastName;
                        emailItem.ReplyToAddress = model.ReplyToAddress;
                        emailItem.Salutation = model.Salutation;
                        emailItem.Subject = model.Subject;
                        emailItem.TestMessage = true;
                    }
                    else
                    {
                        emailItem = new CCM.EmailItem()
                        {
                            CreatedBy = UpdateUser(siteUserPerformingTest),
                            CustomContent1 = model.CustomContent1,
                            CustomContent2 = model.CustomContent2,
                            EmailTo = model.EmailTo,
                            EmailView = "BasicTest",
                            Event = event_,
                            FirstName = model.FirstName,
                            LastName = model.LastName,
                            ReplyToAddress = model.ReplyToAddress,
                            Salutation = model.Salutation,
                            SendStatus = CCM.EmailItem.EmailSendStatus.NotYetSent,
                            Subject = model.Subject,
                            TestMessage = true
                        };
                        ccdr.EFContext.EmailItems.Add(emailItem);
                    }
                    ccdr.Save();
                    model.EmailItemId = emailItem.Id;

                    sendSuccess = SendEmailMessage(ccdr, emailItem, UpdateUser(siteUserPerformingTest), out errorMessage);
                    if (sendSuccess)
                    {
                        viewModel = new MailBasicViewModel()
                        {
                            MailModel = model
                        };
                        SetSharedEventProperties(event_, viewModel, ccdr);
                        return View("MailSent", viewModel);
                    }

                    viewModel = new MailBasicViewModel()
                    {
                        ErrorMessage = errorMessage,
                        MailModel = model
                    };
                }

                if (viewModel == null)
                {
                    viewModel = new MailBasicViewModel()
                    {
                        MailModel = model
                    };
                }
                SetSharedEventProperties(event_, viewModel, ccdr);
                return View("MailTest/TestBasicMail", viewModel);
            }
        }

    }
}
